package com.university.report.common.utils;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName health_report
 * @Author Jinondo
 * @Date 2021/6/13 10:23
 */
public class ExcelUtils {

    public static void exportExcel(HttpServletResponse response, List data, Class classOb,String fileName, String sheetName) throws IOException {
        OutputStream xlsOutputStream = getXlsxOutputStream(response,fileName);
        EasyExcel.write(xlsOutputStream, classOb)
                .sheet(sheetName)
                .registerWriteHandler(new TitleSheetWriteHandler())
                .doWrite(data);
    }

    public static void exportExcel(HttpServletResponse response, List data, Class classOb,String fileName) throws IOException {
        OutputStream xlsxOutputStream = getXlsxOutputStream(response,fileName);
        EasyExcel.write(xlsxOutputStream, classOb)
                .sheet("sheet1")
                .registerWriteHandler(new TitleSheetWriteHandler())
                .doWrite(data);
    }

    public static OutputStream getXlsxOutputStream(HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        // 这里 URLEncoder 防止中文乱码
//        fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        return response.getOutputStream();
    }

    public static OutputStream getXlsOutputStream(HttpServletResponse response,String fileName) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里 URLEncoder 防止中文乱码
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xls");
        return response.getOutputStream();
    }

}
